package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper,CourseBase> implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto courseParamsDto) {

        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<CourseBase>()
                .like(StringUtils.isNotEmpty(courseParamsDto.getCourseName()),CourseBase::getName,courseParamsDto.getCourseName())
                .eq(StringUtils.isNotEmpty(courseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,courseParamsDto.getAuditStatus())
                .eq(CourseBase::getCompanyId,companyId);

        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        IPage<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        List<CourseBase> items = pageResult.getRecords();
        long total = pageResult.getTotal();

        PageResult<CourseBase> courseBasePageResult = new PageResult<CourseBase>(items,total,pageParams.getPageNo(),pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long id, AddCourseDto dto) {

        //合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            //如果不抛出我们自己的异常类型的话 前端收到的异常报出500不友好
//            throw new RuntimeException("课程名称为空");
            XueChengPlusException.cast("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }

        CourseBase courseBaseNew = new CourseBase();
        BeanUtils.copyProperties(dto,courseBaseNew);
        courseBaseNew.setCompanyId(id);
        courseBaseNew.setCreateDate(LocalDateTime.now());
        courseBaseNew.setStatus("203001");
        courseBaseNew.setAuditStatus("202002");

        int insert = courseBaseMapper.insert(courseBaseNew);

        if(insert<=0){
            throw new RuntimeException("添加课程失败");
        }

        CourseMarket courseMarketNew = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarketNew);
        courseMarketNew.setId(courseBaseNew.getId());
        saveCourseMarket(courseMarketNew);
        //在之前已经把base表的信息进行了插入 mapper返回了刚刚插入的id 则可以根据这个id到course_base表中查询到插入的信息 然后把这个信息组装起来返回给前端
        //要返回给前端的是刚刚插入进去的那条新的数据
        CourseBaseInfoDto courseInfo = getCourseBaseInfo(courseBaseNew.getId());

        return courseInfo;
    }


    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //因为课程基本信息表和课程营销表都是一对一 所以他们的id是一致的
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        CourseCategory courseCategoryMt = courseCategoryMapper.selectById(courseBase.getMt());
        String mtName = courseCategoryMt.getName();
        if(mtName != null){
            courseBaseInfoDto.setMtName(mtName);
        }

        CourseCategory courseCategorySt = courseCategoryMapper.selectById(courseBase.getSt());
        String stName = courseCategorySt.getName();
        if(stName != null){
            courseBaseInfoDto.setStName(stName);
        }

        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //课程id
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);

        if(courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int i = courseBaseMapper.updateById(courseBase);
        if(i<=0){
            XueChengPlusException.cast("修改课程基本信息失败");
        }

        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if(courseMarket == null){
            CourseMarket courseMarket1 = new CourseMarket();
            BeanUtils.copyProperties(editCourseDto,courseMarket1);
            courseMarketMapper.insert(courseMarket1);
        }else {
            BeanUtils.copyProperties(editCourseDto,courseMarket);
            int i1 = courseMarketMapper.updateById(courseMarket);
            if(i1<=0){
                XueChengPlusException.cast("修改课程营销信息失败");
            }
        }
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

    @Override
    @Transactional
    public void deleteCourseInfo(Long companyId,Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId()))
            XueChengPlusException.cast("只允许删除本机构的课程");
        if(courseBase.getAuditStatus().equals("202002")) {
            // 删除课程教师信息  这里涉及了两个表的连接 所以可以先用mybatis-plus构造出查询条件 然后在执行删除操作 如果直接deleteById则id是教师的id 而不是课程的id
            //select * from course_teacher where course_id = courseId
            LambdaQueryWrapper<CourseTeacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherLambdaQueryWrapper.eq(CourseTeacher::getCourseId, courseId);
            //delete from course_teacher where course_id = courseId
            courseTeacherMapper.delete(teacherLambdaQueryWrapper);
            // 删除课程计划
            LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teachplanLambdaQueryWrapper.eq(Teachplan::getCourseId, courseId);
            teachplanMapper.delete(teachplanLambdaQueryWrapper);
            // 删除营销信息
            //delete from course_market where course_id = courseId
            courseMarketMapper.deleteById(courseId);
            // 删除课程基本信息
            courseBaseMapper.deleteById(courseId);
        }
    }

    private int saveCourseMarket(CourseMarket courseMarketNew){
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isEmpty(charge)){
            throw new RuntimeException("收费规则不能为空");
        }

        if(charge.equals("201001")){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue()<=0){

//                throw new RuntimeException("课程的价格不能为空并且需要大于0");
                XueChengPlusException.cast("课程的价格不能为空并且需要大于0");
            }
        }

        Long id = courseMarketNew.getId();
        //这个是从数据库里查出来的 是最新的 所以更新的时候传的是这个对象
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if(courseMarket == null){
             return courseMarketMapper.insert(courseMarketNew);
        }else{
            //查出来的这个数据再插入一定是有改变的 所以需要属性拷贝一下 如果查出来不拷贝 不就是把原来的数据又放回去了 没有改变
            BeanUtils.copyProperties(courseMarketNew,courseMarket);
            courseMarket.setId(courseMarketNew.getId());
             return courseMarketMapper.updateById(courseMarket);
        }

    }
}
